package com.sfl.api_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.*;
import com.sfl.api_backend.mapper.DatasetsMapper;
import com.sfl.api_backend.mapper.QuotaMapper;
import com.sfl.api_backend.mapper.TaskMapper;
import com.sfl.api_backend.service.*;
import com.sfl.api_backend.utils.Api.RestResult;
import com.sfl.api_backend.utils.RandomID;
import com.sfl.api_backend.utils.task2json.Task2Json;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author szc
 * @since 2023-01-27
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Resource
    IScriptsService scriptsService;

    @Resource
    IDatasetsService datasetsService;

    @Resource
    IModelsService modelsService;

    @Resource
    IImgsService imgsService;

    @Resource
    TaskMapper taskMapper;

    @Resource
    QuotaMapper quotaMapper;

    @Resource
    DatasetsMapper datasetsMapper;

    @Resource
    ILabelsetsService labelsetsService;

//    @Resource
//    private MqSendService mqSendService;

    @Resource
    private Task2Json task2Json;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public RestResult aboutTask(Task vo) {
        try {
            Wrapper<Scripts> wrapper = new LambdaQueryWrapper<Scripts>().eq(Scripts::getUserId, vo.getUserId());
            Wrapper<Datasets> datasetsWrapper = new LambdaQueryWrapper<Datasets>().eq(Datasets::getUserId, vo.getUserId());
            Wrapper<Models> modelsWrapper = new LambdaQueryWrapper<Models>().eq(Models::getUserId, vo.getUserId())
                    .or()
                    .eq(Models::getUserId, 0);

            Map<String, List> map = new HashMap<>();
            map.put("scripts",scriptsService.list(wrapper));
            map.put("imgset",datasetsService.list(datasetsWrapper));
            map.put("models",modelsService.list(modelsWrapper));
            return RestResult.success(map);
        }
        catch (Exception e){
            return RestResult.error(500,e.getMessage());
        }
    }

    @Override
    public RestResult TaskImgsList(Task vo) {
        try {
            Task task = taskMapper.selectById(vo.getTaskId());
            Wrapper<Imgs> imgsWrapper = new LambdaQueryWrapper<Imgs>().eq(Imgs::getImgsetId, task.getImgsetId());

            Map<String, List> map = new HashMap<>();
            map.put("imgs",imgsService.list(imgsWrapper));
            return RestResult.success(map);
        }
        catch (Exception e){
            return RestResult.error(500,e.getMessage());
        }
    }

    @Override
    public RestResult runTask(Task vo) {
        try{
            // get Task
            Task task = taskMapper.selectById(vo.getTaskId());
            System.out.println(task.getTaskName());

            String TaskJson = task2Json.batchTask2Json(task);

            // update quota
            Wrapper<Quota> quotaWrapper = new LambdaQueryWrapper<Quota>().eq(Quota::getUserId, 597561);
            List<Quota> quotaList = quotaMapper.selectList(quotaWrapper);
            System.out.println(quotaList.get(0).getQuotaNum());
            int newNum = quotaList.get(0).getQuotaNum()-10;
            quotaList.get(0).setQuotaNum(newNum);
            quotaMapper.updateById(quotaList.get(0));

            // create labelsets
            String filePath = uploadPath + task.getUserId() + "/labels/" + task.getImgsetId() + "/";
            System.out.println(filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            Datasets datasets = datasetsMapper.selectById(task.getImgsetId());
            Labelsets labelsets = new Labelsets();
            labelsets.setLabelsetId(RandomID.getRandomID());
            labelsets.setLabelsetName(datasets.getImgsetName());
            labelsets.setLabelsetPath(filePath);
            labelsets.setImgsetId(datasets.getImgsetId());
            labelsets.setUserId(task.getUserId());
            labelsets.setCreateTime(LocalDateTime.now());
            labelsetsService.save(labelsets);

            // send to RabbitMQ
//            mqSendService.sendBatchTask(TaskJson);

            task.setLabelSetId(labelsets.getLabelsetId());
            task.setLastRunTime(LocalDateTime.now());
            taskMapper.updateById(task);

            return RestResult.success();
        }
        catch (Exception e){
            System.out.println(e);
            return RestResult.error(HttpCode.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
